package com.fairy.sso.server.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.fairy.sso.SSOConstants;
import com.fairy.sso.Ticket;
import com.fairy.sso.cache.SSOCache;
import com.fairy.sso.config.FairyConfig;
import com.fairy.sso.server.Factory;
import com.fairy.sso.server.SSOCacheFactory;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = -3170191388656385924L;
	@Autowired(required=true)
	private FairyConfig fairyConfig;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        String service = request.getParameter(SSOConstants.CLIENT_URL);

        if ("cloud".equals(userName) && "cloud".equals(passWord)) {
            Cookie cookie = new Cookie(SSOConstants.SSO_COOKIE_KEY, userName);
            cookie.setPath("/");
            response.addCookie(cookie);

            long time = System.currentTimeMillis();
            String key = userName + time;

            Factory factory = new SSOCacheFactory(); 
        
            String cacheType=fairyConfig.getCacheType();
            SSOCache cache = factory.createSSOCache(cacheType);
            Ticket t=new Ticket();
            
            t.setIp("");

            t.setTime(time);
            t.setUserId(userName);
            
            cache.set(key, t);
            
            if (null != service) {
                StringBuilder url = new StringBuilder();
                url.append(service);
                if (0 <= service.indexOf("?")) {
                    url.append("&");
                } else {
                    url.append("?");
                }
                url.append("ticket=").append(key);
                response.sendRedirect(url.toString());
            } else {
                response.sendRedirect("/sso-server/index.jsp");
            }
        } else {
            response.sendRedirect("/sso-server/index.jsp?service=" + service);
        }
    }
    public void init(ServletConfig config) throws ServletException {  
        super.init(config);  
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());  
}
}